package Demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-01-04
 * Time: 16:52
 */

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 生产者消费者模型: 解耦 (降低耦合,两者关联性)
 *                削峰削谷(给了一个缓冲区,平衡了生产者和消费者的处理能力)
 */
public class Thread_Demo9 {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();//本身带有阻塞等待
                    System.out.println("消费者:" + value);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread producer = new Thread(() -> {
            Random random = new Random();
            while(true) {
                int num = random.nextInt(1001);// 随机产生1-1000的随机数
                try {
                    queue.put(num);
                    System.out.println("生产者: " + num);
                    Thread.sleep(1000); // 生产者线程休眠 1s 确保生产者先生产
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();
        producer.start();
        customer.join(); // 阻塞等待customer 线程结束
        producer.join(); // 阻塞等待producer 线程结束

    }
}
